<template>
  <div class="zt_content">
    <div class="accountSet">
      <div class="accountSetContent">账套管理</div>
    </div>
    <div class="account-list" v-show="!editBook">
      <div class="account-item" v-for="item in Management" :key="item.id" style="position: relative"
        :class="currentAccount == item.id ? 'select-account-item' : ''">
        <img class="useImg" v-if="currentAccount == item.id" src="@/assets/img/use.png" alt />
        <div class="com-name">{{ item.companyName }}</div>
        <div style="margin-top: 20px">
          <div class="product-info">产品类型：{{ item.version || '标准财务版' }}</div>
          <div class="product-info">启用时间：{{ item.enableDate }}</div>
        </div>
        <div :class="currentAccount == item.id ? 'redactDelete' : 'redactDeleteTwo'">
          <el-button size="mini" @click="redact(item)">编辑</el-button>
          <el-button type="primary" size="mini" @click="onUseLog(item)"
            v-if="currentAccount != item.id && item.isAllowLogin == 1">使用</el-button>
          <el-button v-if="item.isLeader == 1" size="mini" @click="remove(item)">删除</el-button>
          <el-button v-else size="mini" @click="removeOut(item)">退出</el-button>
        </div>
      </div>

      <div style="background-color: #ededed" class="add" @click="add">
        <div class="addZT">
          <i class="el-icon-circle-plus-outline"></i>
          <div>新增账套</div>
        </div>
      </div>
    </div>
    <editAccount v-if="editBook" :accountBookId="bookItem.id" @onCancel="editBook = false" @onAddSubmit="onAddSubmit">
    </editAccount>
    <PopupReminder ref="reminderRef" :tipsData="tipsData" @onConfirm="onYes"></PopupReminder>
    <el-dialog title :visible.sync="accountDialogVisible" :show-close="false" width="550px">
      <span slot="title"></span>
      <span slot="footer"></span>
      <div class="dialog_view">
        <div class="create-card">
          <div class="create-title">创建账套</div>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="form-view">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="form.companyName"></el-input>
            </el-form-item>
            <!-- <el-form-item label="启用时间" prop="enableDate">
              <el-date-picker type="date" placeholder="启用时间" v-model="form.enableDate" style="width: 100%"
                :picker-options="pickerOptions" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item> -->
            <el-form-item label="币种符号" prop="currencyType">
              <j-dict-select-tag type="select" dictCode="currency_type" style="width:100%;" v-model="form.currencyType"
                placeholder="请选择币种符号"></j-dict-select-tag>
            </el-form-item>
            <el-button class="btn" type="primary" @click="nextStep">下一步</el-button>
          </el-form>
        </div>
      </div>
    </el-dialog>

    <!-- 版本选择弹窗 -->
    <el-dialog title :visible.sync="versionDialogVisible" :show-close="false" width="1200px" custom-class="version-dialog">
      <span slot="title"></span>
      <span slot="footer"></span>
      <div class="version-select-view">
        <div class="select-title">请选择您要使用的版本</div>
        <div class="version-list">
          <div v-for="(version, index) in versionList" :key="index" class="version-card">
            <div class="version-name">{{version.name}} <div class="version-user-limit" v-if="version.name === '必用版'">不限用户</div></div>
            <div class="version-desc">{{version.description}}</div>
            <el-button class="free-trial-btn" type="primary" @click="selectVersion(version)">免费试用</el-button>
            <div class="version-date">免费试用期限为7天</div>
          </div>
        </div>
        <div style="display: flex; justify-content: center; margin-top: .875rem;">
          <img width="70%" class="logo" :src="require('../../../assets/login/logo_trans.png')" alt />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PopupReminder from '@/views/components/popupReminder.vue'
import Vue from 'vue'
import { USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'
import { getAction, postAction } from '@/api/manage'
import { deleteAction } from '../../../api/manage'
import { ACCESS_TOKEN } from '../../../store/mutation-types'
import createAccount from '../../user/createAccount.vue'
import JDictSelectTag from '../../../components/dict/JDictSelectTag.vue'
import editAccount from './redactMessage/index.vue'
import { mapActions } from 'vuex'
import { getTimeYMD } from '@/utils/DateFormatter'

export default {
  name: 'ManagementZT',
  inject: ['closeAll'],
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      // 传递弹框数据 
      tipsData: { tipsWords: '', tipsMark: '', tipsState: '' },
      activeIndex: 0,
      index: '',
      // 管理
      userInfo: Vue.ls.get(USER_INFO),
      Management: [],
      currentAccount: '', // 使用中账套id
      bookItem: '', // 要处理的临时账套
      editBook: false,

      accountDialogVisible: false,
      form: {
        companyName: '',
        // enableDate: '',
        currencyType: '1',
      },
      moneyoptions: [
        {
          value: '1',
          label: 'RMB ￥',
        },
        {
          value: '2',
          label: '美元 $',
        },
      ],
      rules: {
        companyName: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
        ],
        // enableDate: [
        //   { type: 'string', required: true, message: '请选择启用日期', trigger: 'change' }
        // ],
        currencyType: [
          { required: true, message: '请选择货币', trigger: 'change' }
        ]
      },
      timer: null,
      number: 20,
      // 版本选择
      versionDialogVisible: false,
      selectedVersion: null,
      versionList: [ // 版本列表
        {
          name: '必用版',
          description: '小微商家必备'
        },
        {
          name: '专业版',
          description: '全行业通用，功能强大'
        },
        {
          name: '高级版',
          description: '特色功能模块更智能'
        },
        {
          name: '标准财务版',
          description: '进销存财务一体化管理'
        }
      ],
    }
  },
  components: { PopupReminder, createAccount, JDictSelectTag, editAccount },
  created() {
    console.log(Date.now(), '1111')
  },
  mounted() {
    this.getAccountList()
    this.editBook = false
  },
  methods: {
    ...mapActions(['Logout']),
    // 获取账套列表
    getAccountList() {
      const that = this
      let userInfo = Vue.ls.get(USER_INFO)
      let accountInfo = Vue.ls.get(ACCOUNT_BOOK) || {}
      getAction(`accountbookinfo/xghAccountBook/getAccountBookByUserId/${userInfo.id}`).then((res) => {
        if (res.code == 200) {
          that.Management = res.result
          // that.currentAccount =
          //   that.currentAccount && that.currentAccount.length ? that.currentAccount : that.Management[0].id
          that.Management.forEach((item) => {
            if (accountInfo.id && item.id == accountInfo.id) {
              Vue.ls.set(ACCOUNT_BOOK, item)
              that.currentAccount = item.id
              let query = that.$route.query
              if (query.editBook) {
                that.redact(item)
              }
            }
          })
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },

    redactMessage() {
      this.$router.push('/setting/ManagementZT/redactMessage/index')
    },
    redact(item) {
      this.bookItem = item
      this.editBook = true

      // this.tipsData.tipsWords = '你确定要编辑吗？</br>是否继续？'
      // this.tipsData.tipsMark = 'onNewOreder'
      // this.$refs.reminderRef.dialogVisible = true
    },
    onYes(data) {
      if (data === 'onNewOreder') {
        // 新增账套
        console.log('新增账套')
        this.$router.push('/setting/ManagementZT/redactMessage/index')
      } else if (data === 'useLog') {
        if (getTimeYMD() < this.bookItem.periodOfUse) {
            // 账套还没有到期
            Vue.ls.set('account-no-money', false)
            this.editAccountInfo(this.bookItem)
          } else {
            // 只有管理员可以续费
            if (this.bookItem.isLeader == 1) {
              // 账套到期
              Vue.ls.set('account-no-money', true)
              this.editAccountInfo(this.bookItem)
            } else {
              this.$elMessage.warning('账套已到期，请联系管理员续费!')
            }
          }
      } else if (data === 'remove') {
        // 确定删除该账套
        this.deleteAccountInfo(this.bookItem)
      } else if (data === 'removeOut') {
        // 退出账套
        this.deleteAccountInfo(this.bookItem)
      }
    },
    // 使用账套
    onUseLog(item) {
      this.tipsData.tipsWords = '你确定要使用该账套吗？</br>是否继续？'
      this.tipsData.tipsMark = 'useLog'
      this.$refs.reminderRef.dialogVisible = true
      this.bookItem = item
    },
    // 删除账套
    remove(item) {
      this.tipsData.tipsWords = '你确定要删除该账套吗？</br>是否继续？'
      this.tipsData.tipsMark = 'remove'
      this.$refs.reminderRef.dialogVisible = true
      this.bookItem = item
    },
    // 退出账套
    removeOut(item) {
      this.tipsData.tipsWords = '你确定要退出该账套吗？</br>是否继续？'
      this.tipsData.tipsMark = 'removeOut'
      this.$refs.reminderRef.dialogVisible = true
      this.bookItem = item
    },
    // 更新账套
    editAccountInfo(item) {
      const that = this
      let number = 20
      const loading = that.$loading({
        lock: true,
        text: '账套切换中，请耐心等待，预计剩余20s...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      });
      if (that.timer) {
        clearInterval(that.timer)
      }
      that.timer = setInterval(() => {
        setTimeout(() => {
          if (number > 0) {
            number--
            loading.setText(`账套切换中，请耐心等待，预计剩余${number}s...`)
          } else {
            clearInterval(that.timer)
            loading.close()
          }
        }, 0);
      }, 1000)
      postAction('accountbookusing/xghAccountBookUserUsing/updateByUserId', {
        accountBookId: item.id,
        userId: this.userInfo.id,
      }).then((res) => {
        if (res.code == 200) {
          Vue.ls.set(ACCOUNT_BOOK, item)
          this.currentAccount = item.id
          // 切换账套需要关闭其他标签
          this.closeAll()
          this.getOpenAccountFlag()
          loading.close()
          // 发送消息
          console.log('发送消息---', item)
          this.$EventBus.$emit('ISCHANGE', item)
          this.$EventBus.$emit('changeAccountBook')
          let userPerms = res.result || {}
          this.$lcStorage.set('userPermissions', userPerms)
        }
      })
    },
    // 获取期初信息
    getOpenAccountFlag() {
      getAction('/openAccount/getOpenAccountType', {}).then((res) => {
        if (res.code === 200) {
          if (!res.result) {
            // 开单标志，res.result为null表示新账套
            this.toSystemConfiguration()
            this.$store.commit('SET_OPEN_ACCOUNT_VALUE', 0)
          } else {
            this.$store.commit('SET_OPEN_ACCOUNT_VALUE', Number(res.result.value))
            // 开单标志，3表示已经开账，其他状态为开账中，需要跳转开账页面
            if (res.result.value != 3) {
              this.toSystemConfiguration()
            } else {
              // 账套过期，跳转续费页面
              if(Vue.ls.get('account-no-money')) {
                console.log('账套过期，跳转续费页面') 
                this.$router.push({ name: "setting-buy-accountBookPay" }).catch(err => {})
              }
            }
          }
        }
      })
    },
    toSystemConfiguration() {
       // 账套没有过期，跳转到开账页面，过期只能跳转续费页面
       if(!Vue.ls.get('account-no-money')) {
        this.$router.push({ name: "business-SystemConfiguration" }).catch(err => {
        })
      } else {
        this.$router.push({ name: "setting-buy-accountBookPay" }).catch(err => {
        })
      }
    },
    // 确认删除账套
    deleteAccountInfo(item) {
      const that = this
      postAction('/accountbookinfo/xghAccountBook/exitAccountBook', {
        isAllowLogin: item.isAllowLogin,
        isLeader: item.isLeader,
        xghAccountBookId: item.id,
        xghSysUserId: this.userInfo.id,
      }).then((res) => {
        console.log(res)
        if (res.code == 200) {
          if (item.id == this.currentAccount) {
            // 退出登录
            that.loginOut(item)
          } else {
            // 刷新账套
            that.$elMessage.success(res.message)
            this.onAddSubmit()
          }
        } else {
          that.$elMessage.warning(res.message)
        }
      })
    },
    // 确认退出账套
    quitAccountInfo(item) {
      const that = this
      postAction('accountbookinfo/xghAccountBook/exitAccountBook', {
        isAllowLogin: 0,
        isLeader: 0,
        xghAccountBookId: item.id,
        xghSysUserId: this.userInfo.id,
      }).then((res) => {
        console.log(res)
        if (res.code == 200) {
          if (item.id == this.currentAccount) {
            // 退出登录
            that.loginOut(item)
          } else {
            // 退出成功, 刷新账套
            that.$elMessage.success('退出成功!')
            this.onAddSubmit()
          }
        } else {
          that.$elMessage.warning(res.message)
        }
      })
    },
    // 解除绑定关系, 并退出登录
    loginOut(item) {
      const that = this
      this.Logout({}).then(() => {
        // update-begin author:wangshuai date:20200601 for: 退出登录跳转登录页面
        that.$router.push({ path: '/user/login' })
        window.location.reload()
        // update-end author:wangshuai date:20200601 for: 退出登录跳转登录页面
      })
        .catch((err) => {
          that.$elMessage.error({
            title: '错误',
            description: err.message,
          })
        })
    },
    // 跳转到新增账套
    async add() {
      // this.accountDialogVisible = true
      let result = await getAction('/accountbookinfo/xghAccountBook/checkFreeAccountBookNumber')
      if (result.success) {
        this.accountDialogVisible = true
      } else {
        this.$elMessage.error(result.message)
      }
    },
    nextStep() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 判断公司名称是否存在
          let result = await postAction('/accountbookinfo/xghAccountBook/companyNameExists', {
            companyName: this.form.companyName
          })
          if (result.success) {
            if(result.result) {
              this.versionDialogVisible = true;
            } else {
              this.$elMessage.error('公司名称已存在')
            }
          } else {
            this.$elMessage.error(result.message)
          } 
        }
      })
    },
    selectVersion(version) {
      this.selectedVersion = version;
      this.form.version = version.name;
      this.onSubmit();
      
    },
    onSubmit() {
      const that = this
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log('this.form', this.form)
          const loading = that.$loading({
            lock: true,
            text: '账套正在新建中, 请耐心等待，预计剩余20s...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.8)',
          });
          if (that.timer) {
            clearInterval(that.timer)
          }
          that.timer = setInterval(() => {
            setTimeout(() => {
              if (that.number > 0) {
                that.number--
                loading.setText(`账套正在新建中，请耐心等待，预计剩余${that.number}s...`)
              } else {
                clearInterval(that.timer)
                loading.close()
              }
            }, 0);
          }, 1000)
          postAction('/accountbookinfo/xghAccountBook/add', this.form).then(res => {
            clearInterval(that.timer)
            loading.close()
            if (res.success) {
              this.$elMessage.success(res.message)
              this.accountDialogVisible = false;
              this.versionDialogVisible = false;
              this.onAddSubmit()
              this.$refs.form.resetFields();
            } else {
              this.$elMessage.error(res.message)
            }
          })
        }
      })
    },
    onAddSubmit() {
      this.editBook = false
      this.getAccountList()
      this.$EventBus.$emit('changeBook')
    }
  },
}
</script>

<style scoped lang='scss'>
.add {
  width: 6rem;
  height: 200px; //3.750234rem;
  justify-content: center;
  align-items: center;
  display: flex;
  border-radius: 0.093756rem;
  margin-left: 0.18rem;
}

::v-deep .el-icon-circle-plus-outline {
  font-size: 0.56rem;
}

.account-list {
  // width: 100%;
  display: flex;
  flex-wrap: wrap;
  padding: 0.55rem;

  // justify-content: space-between;

  flex-wrap: wrap;

  .account-item {
    margin: 0 10px 20px 10px;
    width: 6rem;
    height: 200px; //3.750234rem;
    border: 1px solid #77c1ff;
    opacity: 1;
    border-radius: 0.187512rem;
    // padding-left: 0.543784rem;
    // padding-top: 0.768798rem;
    padding: 30px 30px 0;
    background-color: #e3f6ff;
  }

  .add-account {
    border: 0.018751rem solid #cbced3;
  }
}

.com-name {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 600;
  // line-height: 0.412526rem;
  opacity: 1;
}

.product-info {
  font-size: 12px; //0.225014rem;
  font-family: PingFang SC;
  font-weight: 400;
  // line-height: 0.356272rem;
  opacity: 1;
}

.accountSet {
  padding: 0.37rem;
  font-size: 16px;
  color: #1b94fb;
}

.accountSetContent {
  color: #1b94fb;
  box-sizing: border-box;
  font-size: 16px;
  line-height: 22px;
  font-weight: 600;
  padding-bottom: 0.375023rem;
  border-bottom: 0.018751rem solid #ddd;
  font-family: PingFang SC;
}

.select-account-item {
  background-color: #1993fb !important;
  color: #fff !important;
}

.redactDelete {
  position: absolute;
  // width: 3.750234rem;
  // left: 3.562723rem;
  // top: 2.906432rem;
  right: 30px;
  bottom: 20px;
}

.redactDeleteTwo {
  position: absolute;
  right: 30px;
  bottom: 20px;
}

.el-icon-circle-plus-outline {
  color: #666;
}

.addZT {
  display: flex;
  font-size: 0.300019rem;
  color: #666666;

  div {
    line-height: 0.56rem;
    margin-left: 0.093756rem;
  }
}

.el-icon-circle-plus-outline::before {
  width: 0.543784rem;
  height: 0.543784rem;
}

.useImg {
  position: absolute;
  // left: 5.100319rem;
  top: -0.018751rem;
  right: -0.018751rem;
}

.dialog_view {
  width: 100%;
  display: flex;
  justify-content: center;
}

.create-card {
  position: relative;
  margin-top: -0.225014rem;
  width: 300px;
  background: #ffffff;
  opacity: 1;
  border-radius: 0.375023rem;
  display: flex;
  flex-direction: column;
  justify-content: center;

  .create-title {
    font-size: 30px;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 42px;
    color: #666666;
    display: flex;
    justify-content: center;
    margin: 20px 0;
  }

  .btn {
    width: 100%;
    margin-top: 0.825052rem;
    display: inline-block;
  }
}

::v-deep .el-dialog__footer {
  padding: 0px;
}

::v-deep .el-dialog__header {
  padding: 0px;
}

.version-select-view {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 50px 0;

  .select-title {
    font-size: 24px;
    font-family: PingFang SC;
    font-weight: 500;
    line-height: 32px;
    color: #666666;
    opacity: 1;
    margin-bottom: 50px;
  }

  .version-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 20px;
    padding: 0 20px;
    width: 100%;
    max-width: 1100px;
  }

  .version-card {
    padding: 20px;
    transition: all 0.3s;
    width: 240px;
    height: 180px;
    background: #ffffff;
    border: 1.5px solid #77c1ff;
    opacity: 1;
    border-radius: 8px;
    color: #666666;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    }

    .version-name {
      font-size: 20px;
      font-weight: 600;
      color: #0082F1;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
    }

    .version-user-limit {
      padding: 2px 6px;
      background: #F1F1F1;
      color: #999999;
      font-size: 12px;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 10px;
      font-weight: normal;
      letter-spacing: 1px;
    }

    .version-desc {
      font-size: 14px;
      color: #666;
      margin-bottom: 15px;
    }

    .free-trial-btn {
      font-size: 14px;
      width: 100px;
      margin-bottom: 10px;
    }

    .version-date {
      font-size: 12px;
      color: #999999;
    }
  }
}

::v-deep .version-dialog {
  background: #E3F6FF;
  .el-dialog__body {
    background: #E3F6FF;
  }
}
</style>